package cn.signalpha.modules.shop.service;

import cn.signalpha.common.constant.MsgConstant;
import cn.signalpha.common.utils.Assert;
import cn.signalpha.core.log.exception.ServiceException;
import cn.signalpha.core.tool.utils.BeanUtil;
import cn.signalpha.core.tool.utils.DateUtil;
import cn.signalpha.modules.shop.entity.Coupon;
import cn.signalpha.modules.shop.entity.CouponUser;
import cn.signalpha.modules.shop.mapper.CouponMapper;
import cn.signalpha.modules.shop.vo.CouponVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 服务类
 *
 * @author signalpha
 */
@Service
@AllArgsConstructor
public class CouponService extends ServiceImpl<CouponMapper, Coupon> {

	private final CouponUserService couponUserService;

	/**
	 * 自定义分页
	 */
    public IPage<CouponVO> selectCouponPage(IPage<CouponVO> page, Map<String, Object> params) {
        return page.setRecords(baseMapper.selectCouponPage(page, params));
    }

	/**
	 * 领取优惠券
	 */
	@Transactional(rollbackFor = Exception.class)
    public boolean receiveCoupon(Long couponId, Long userId, Integer type) {
		Date date = DateUtil.now();
		Coupon coupon = getById(couponId);
		Assert.isNull(coupon, MsgConstant.OBJECT_NULL);
		Assert.isTrue(coupon.getStatus() != 0, "优惠券已暂停使用");
		Assert.isTrue(coupon.getLastTotal() > 0, "优惠券已发完");

		Date beginTime, endTime;
		if(coupon.getIsFixedTime() == 1){
			beginTime = coupon.getUseStartTime();
			endTime = coupon.getUseEndTime();
		}else{
			beginTime = date;
			endTime = DateUtil.plusDays(date, coupon.getDay());
		}

		int count = couponUserService.isGet(coupon.getId(), userId);
		Assert.isTrue(count == 0, "请不要重复领取");
		if(coupon.getLimitNum() > 0){
			long total = couponUserService.count(Wrappers.<CouponUser>lambdaQuery().eq(CouponUser::getUserId, userId).eq(CouponUser::getCouponId, coupon.getId()));
			if(total >= coupon.getLimitNum()){
				throw new ServiceException("已达到每人限领上限");
			}
		}

		CouponUser couponUser = Objects.requireNonNull(BeanUtil.copy(coupon, CouponUser.class));
		couponUser.setId(null);
		couponUser.setCouponId(coupon.getId());
		couponUser.setType(type);
		couponUser.setUserId(userId);
		couponUser.setStatus(0);
		couponUser.setBeginTime(beginTime);
		couponUser.setEndTime(endTime);
		couponUser.setCreateTime(date);
		couponUser.setUpdateTime(date);
		couponUserService.save(couponUser);
    	return updateById(Coupon.builder().id(couponId).lastTotal(coupon.getLastTotal() - 1).updateTime(date).build());
    }

	/**
	 * 获取商品可用的优惠券
	 */
    public List<Coupon> listByGoods(Long goodsId) {
		return baseMapper.selectList(Wrappers.<Coupon>query().lambda()
			.or(i -> i.eq(Coupon::getUseType, 3).or().apply("FIND_IN_SET ('" + goodsId + "',primary_key)"))
			.eq(Coupon::getType, 1).eq(Coupon::getStatus, 1).gt(Coupon::getLastTotal, 0)
			.orderByDesc(Coupon::getId)
		);
    }
}

